package com.yunkaweilai.android.activity.operation.consumption.jici;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.interfaces.UpdateJiciInterfaces;
import com.yunkaweilai.android.model.jici.CreateJiciStrModel;
import com.yunkaweilai.android.model.jici.MemberJiciListModel;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.UpdateJiciNumDialog;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 计次消费
 * Created by Administrator on 2017/7/31.
 */

public class JiciListActivity extends BaseActivity implements UpdateJiciInterfaces {


    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.id_tv_name)
    TextView idTvName;
    @BindView(R.id.id_tvcard_number)
    TextView idTvcardNumber;
    @BindView(R.id.id_tv_card_infor)
    TextView idTvCardInfor;
    @BindView(R.id.id_listview)
    ListView idListview;
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    private MemberJiciListModel memberJiciListModel;

    public static final String JICI_MEMBER_ID = "JICI_MEMBER_ID";
    private String SelectedGoodsStr = "";//选择字符串
    private String member_id;
    private Gson gson = new Gson();
    private CommonAdapter<MemberJiciListModel.DataBean.JiciGoodsListBean> adapter;
    private ArrayList<MemberJiciListModel.DataBean.JiciGoodsListBean> list = new ArrayList<>();

    public static void actionStart(Context context, String member_id) {
        Intent intent = new Intent(context, JiciListActivity.class);
        intent.putExtra(JICI_MEMBER_ID, member_id);
        context.startActivity(intent);
    }


    private void initHeadView() {
        MemberHeadModel model = memberJiciListModel.getData().getMemberInfo();
        Utils.MemberHeadImg(mAc, model.getMember_avatar(), model.getMember_sex(), idImgHead);
        idTvName.setText(model.getMember_name() + " (" + model.getLevel_name() + ": " + model.getCard_no() + ")");
        idTvCardInfor.setText("折扣：" + model.getDiscount() / 10 + "折   积分：" + model.getMember_points() + "   余额：" + model.getMember_price());

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jici_list);
        ButterKnife.bind(this);
        member_id = getIntent().getStringExtra(JICI_MEMBER_ID);
        new TitleBuilder(mAc).setLeftImage(R.mipmap.ic_go_back).setTitleText("计次消费")
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).setRightText("下一步").setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(SelectedGoodsStr)) {
                    showToast("选择扣除数量");
                } else {
                    JiciOperaOrderActivity.actionStart(mAc, memberJiciListModel.getData().getMemberInfo(), SelectedGoodsStr);
                }
            }
        });
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });
        initAdapter();
        initHttp();
    }

    private void initAdapter() {
        adapter = new CommonAdapter<MemberJiciListModel.DataBean.JiciGoodsListBean>(mAc, R.layout.item_member_jici_list, list) {
            @Override
            protected void convert(ViewHolder viewHolder, final MemberJiciListModel.DataBean.JiciGoodsListBean item, int position) {
                viewHolder.setText(R.id.id_tv_jici_name, item.getGoods_name());
                viewHolder.setText(R.id.id_tv_nums, item.getCount() + "");
                final TextView idTvAddNum = viewHolder.getView(R.id.id_tv_add_num);
                ImageView idImgDel = viewHolder.getView(R.id.id_img_del);
                final ImageView idImgAdd = viewHolder.getView(R.id.id_img_add);
                idTvAddNum.setText(item.getBuy_nums() + "");
                TextView idTvTime = viewHolder.getView(R.id.id_tv_time);
                String times = "";
                if (item.getGoods_list().size() == 1) {
                    if (item.getGoods_list().get(0).isIs_validity()) {
                        times = times + "<font color='#F53435'>" + item.getGoods_list().get(0).getValidity_content() + "</font>";
                    } else {
                        times = times + item.getGoods_list().get(0).getValidity_content();
                    }
                } else {
                    for (int i = 0; i < item.getGoods_list().size(); i++) {
                        MemberJiciListModel.DataBean.JiciGoodsListBean.GoodlistBeans goodlistBeans = item.getGoods_list().get(i);
                        if (goodlistBeans.isIs_validity()) {
                            times = times +"<font color='#F53435'>" + goodlistBeans.getValidity_content() + "(" + goodlistBeans.getGoods_num() + "次)</font>";
                        } else {
                            times = times + goodlistBeans.getValidity_content() + "(" + goodlistBeans.getGoods_num() + "次)";
                        }
                        if (i + 1 != item.getGoods_list().size()) {
                            times = times + "<Br/>";
                        }
                    }
                }
                Log.d(TAG, "convert: " + times);
                idTvTime.setText(Html.fromHtml(times));

                //减少
                idImgDel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        double buy_nums = Double.parseDouble(item.getBuy_nums());
                        if (buy_nums > 0) {
                            initGetStr(item.getGoods_id(), buy_nums - 1 > 0 ? buy_nums - 1 : 0, buy_nums - 1 > 0 ? "0" : "1");
                        }
                    }
                });
                idTvAddNum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UpdateJiciNumDialog dialog = new UpdateJiciNumDialog(mAc, item.getGoods_id(), JiciListActivity.this,"修改数量");
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.show();
                    }
                });
                //添加
                idImgAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        double buy_nums = Double.parseDouble(item.getBuy_nums());
                        if (buy_nums + 1 > Double.parseDouble(item.getCount())) {

                        } else {
                            initGetStr(item.getGoods_id(), buy_nums + 1, "0");
                        }
                    }
                });
            }
        };
        idListview.setAdapter(adapter);

    }

    private void initGetStr(final String goods_id, double nums, final String isDel) {
        showProgressDialog();

        HttpRequest.postUrl(Api.CREATE_SELECTED_JICI)
                .addParams("member_id", member_id)
                .addParams("goods_id", goods_id)
                .addParams("goods_num", nums + "")
                .addParams("SelectedGoodsStr", SelectedGoodsStr)
                .addParams("isDel", isDel)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            CreateJiciStrModel createJiciStrModel = gson.fromJson(json, CreateJiciStrModel.class);
                            SelectedGoodsStr = createJiciStrModel.getData().getOrderInfo().getSelectedGoodsStr();
                            if ("1".equals(isDel)) {
                                for (int j = 0; j < list.size(); j++) {
                                    MemberJiciListModel.DataBean.JiciGoodsListBean jiciGoodsListBean = list.get(j);
                                    if (jiciGoodsListBean.getGoods_id().equals(goods_id)) {
                                        jiciGoodsListBean.setBuy_nums("0");
                                    }
                                }
                            } else {
                                for (int i = 0; i < createJiciStrModel.getData().getGoodsList().size(); i++) {
                                    CreateJiciStrModel.DataBean.GoodsListBean goodsListBean = createJiciStrModel.getData().getGoodsList().get(i);
                                    for (int j = 0; j < list.size(); j++) {
                                        MemberJiciListModel.DataBean.JiciGoodsListBean jiciGoodsListBean = list.get(j);
                                        if (jiciGoodsListBean.getGoods_id().equals(goodsListBean.getGoods_id())) {
                                            jiciGoodsListBean.setBuy_nums(goodsListBean.getGoods_num());
                                        }
                                    }
                                }
                            }
                            adapter.notifyDataSetChanged();
                            dismissProgressDialog();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(R.string.http_error);
                        dismissProgressDialog();
                    }
                });


    }


    private void initHttp() {
        HttpRequest.postUrl(Api.JICI_MEMBER_LIST)
                .addParams("member_id", member_id)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            memberJiciListModel = gson.fromJson(json, MemberJiciListModel.class);

                            list.clear();
//                            //去掉为0的计次
//                            for (int i = 0 ; i<memberJiciListModel.getData().getJiciGoodsList().size();i++){
//                                if (!memberJiciListModel.getData().getJiciGoodsList().get(i).getCount().equals("0")){
//                                    list.add(memberJiciListModel.getData().getJiciGoodsList().get(i));
//                                }
//                            }
                            list.addAll(memberJiciListModel.getData().getJiciGoodsList());
                            initHeadView();
                            adapter.notifyDataSetChanged();
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showContent();
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }

                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });

    }


    @Override
    public void refreshNum(String goods_id, String num) {
        initGetStr(goods_id, Double.parseDouble(num), "0");
    }
}
